<template>
  <view class="add-baby-container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-content">
        <u-icon name="arrow-left" size="20" color="#333" @click="goBack"></u-icon>
        <text class="navbar-title">添加宝宝信息</text>
        <view class="navbar-right"></view>
      </view>
    </view>
    
    <!-- 表单内容 -->
    <view class="form-container">
      <!-- 宝宝头像 -->
      <view class="avatar-section">
        <view class="avatar-wrapper" @click="chooseAvatar">
          <image 
            v-if="babyInfo.avatar" 
            :src="babyInfo.avatar" 
            class="baby-avatar"
            mode="aspectFill"
          ></image>
          <view v-else class="avatar-placeholder">
            <u-icon name="camera" size="30" color="#c0c0c0"></u-icon>
            <text class="avatar-text">添加照片</text>
          </view>
        </view>
      </view>
      
      <!-- 基本信息表单 -->
      <view class="form-section">
        <text class="section-title">基本信息</text>
        
        <!-- 宝宝姓名 -->
        <view class="form-item">
          <text class="form-label">宝宝姓名 <text class="required">*</text></text>
          <u-input 
            v-model="babyInfo.name"
            placeholder="请输入宝宝姓名"
            :border="true"
            :clearable="true"
            maxlength="20"
            @input="validateForm"
          ></u-input>
        </view>
        
        <!-- 性别选择 -->
        <view class="form-item">
          <text class="form-label">性别 <text class="required">*</text></text>
          <view class="gender-selector">
            <view 
              class="gender-option"
              :class="{ active: babyInfo.gender === 'male' }"
              @click="selectGender('male')"
            >
              <u-icon name="man" size="20" color="#007aff"></u-icon>
              <text class="gender-text">男宝</text>
            </view>
            <view 
              class="gender-option"
              :class="{ active: babyInfo.gender === 'female' }"
              @click="selectGender('female')"
            >
              <u-icon name="woman" size="20" color="#ff69b4"></u-icon>
              <text class="gender-text">女宝</text>
            </view>
          </view>
        </view>
        
        <!-- 出生日期 -->
        <view class="form-item">
          <text class="form-label">出生日期 <text class="required">*</text></text>
          <view class="date-picker" @click="showDatePicker">
            <text class="date-text" :class="{ placeholder: !babyInfo.birthDate }">
              {{ babyInfo.birthDate || '请选择出生日期' }}
            </text>
            <u-icon name="calendar" size="16" color="#c0c0c0"></u-icon>
          </view>
        </view>
      </view>
      
      <!-- 身体数据 -->
      <view class="form-section">
        <text class="section-title">身体数据</text>
        
        <!-- 出生体重 -->
        <view class="form-item">
          <text class="form-label">出生体重</text>
          <view class="input-with-unit">
            <u-input 
              v-model="babyInfo.birthWeight"
              type="digit"
              placeholder="请输入体重"
              :border="true"
              :clearable="true"
            ></u-input>
            <text class="unit-text">kg</text>
          </view>
        </view>
        
        <!-- 出生身高 -->
        <view class="form-item">
          <text class="form-label">出生身高</text>
          <view class="input-with-unit">
            <u-input 
              v-model="babyInfo.birthHeight"
              type="digit"
              placeholder="请输入身高"
              :border="true"
              :clearable="true"
            ></u-input>
            <text class="unit-text">cm</text>
          </view>
        </view>
        
        <!-- 当前体重 -->
        <view class="form-item">
          <text class="form-label">当前体重</text>
          <view class="input-with-unit">
            <u-input 
              v-model="babyInfo.currentWeight"
              type="digit"
              placeholder="请输入当前体重"
              :border="true"
              :clearable="true"
            ></u-input>
            <text class="unit-text">kg</text>
          </view>
        </view>
        
        <!-- 当前身高 -->
        <view class="form-item">
          <text class="form-label">当前身高</text>
          <view class="input-with-unit">
            <u-input 
              v-model="babyInfo.currentHeight"
              type="digit"
              placeholder="请输入当前身高"
              :border="true"
              :clearable="true"
            ></u-input>
            <text class="unit-text">cm</text>
          </view>
        </view>
      </view>
      
      <!-- 其他信息 -->
      <view class="form-section">
        <text class="section-title">其他信息</text>
        
        <!-- 备注 -->
        <view class="form-item">
          <text class="form-label">备注</text>
          <textarea 
            v-model="babyInfo.notes"
            class="textarea-input"
            placeholder="记录一些特殊情况或备注信息"
            maxlength="200"
            :auto-height="true"
          ></textarea>
        </view>
      </view>
    </view>
    
    <!-- 底部按钮 -->
    <view class="bottom-actions">
      <u-button 
        class="save-btn"
        type="primary"
        size="large"
        :loading="saving"
        :disabled="!isFormValid"
        @click="saveBabyInfo"
      >
        保存
      </u-button>
    </view>
    
    <!-- 日期选择器 -->
    <u-datetime-picker
      ref="datetimePicker"
      v-model="datePickerValue"
      mode="date"
      :max-date="maxDate"
      :min-date="minDate"
      @confirm="onDateConfirm"
      @cancel="onDateCancel"
    ></u-datetime-picker>
  </view>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { BabyProfileService } from '@/services/database';
import { uploadFile, STORAGE_BUCKETS, getCurrentUser } from '@/config/supabase';

// 宝宝信息接口
interface BabyInfo {
  name: string;
  gender: 'male' | 'female' | '';
  birthDate: string;
  avatar?: string;
  birthWeight?: string;
  birthHeight?: string;
  currentWeight?: string;
  currentHeight?: string;
  notes?: string;
}

@Component
export default class AddBabyPage extends Vue {
  // 数据属性
  babyInfo: BabyInfo = {
    name: '',
    gender: '',
    birthDate: '',
    avatar: '',
    birthWeight: '',
    birthHeight: '',
    currentWeight: '',
    currentHeight: '',
    notes: ''
  };
  
  saving: boolean = false;
  datePickerValue: number = Date.now();
  maxDate: number = Date.now();
  minDate: number = new Date('2020-01-01').getTime();
  
  // 计算属性
  get isFormValid(): boolean {
    return !!(this.babyInfo.name && this.babyInfo.gender && this.babyInfo.birthDate);
  }
  
  /**
   * 页面加载时初始化
   */
  onLoad() {
    // 设置默认日期为今天
    this.datePickerValue = Date.now();
  }
  
  /**
   * 返回上一页
   */
  goBack() {
    uni.navigateBack();
  }
  
  /**
   * 选择宝宝头像
   */
  chooseAvatar() {
    uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        this.uploadAvatar(tempFilePath);
      },
      fail: (err) => {
        console.error('选择图片失败:', err);
        uni.showToast({
          title: '选择图片失败',
          icon: 'none'
        });
      }
    });
  }
  
  /**
   * 上传头像
   * @param filePath 图片文件路径
   */
  async uploadAvatar(filePath: string) {
    uni.showLoading({ title: '上传中...' });
    
    try {
      // 获取当前用户
      const currentUser = await getCurrentUser();
      if (!currentUser) {
        throw new Error('用户未登录');
      }
      
      // 生成唯一文件名
      const fileName = `baby_avatar_${Date.now()}.jpg`;
      const fileKey = `${currentUser.id}/${fileName}`;
      
      // 读取文件数据
      const fileData = await this.readFileAsBlob(filePath);
      
      // 上传到Supabase存储
      const publicUrl = await uploadFile(
        STORAGE_BUCKETS.BABY_PHOTOS,
        fileKey,
        fileData
      );
      
      if (publicUrl) {
        this.babyInfo.avatar = publicUrl;
        uni.hideLoading();
        uni.showToast({
          title: '上传成功',
          icon: 'success'
        });
      } else {
        throw new Error('上传失败');
      }
    } catch (error: unknown) {
      uni.hideLoading();
      console.error('上传头像失败:', error);
      const errorMessage = error instanceof Error ? error.message : '上传失败';
      uni.showToast({
        title: errorMessage,
        icon: 'none'
      });
    }
  }
  
  /**
   * 读取文件为Blob对象
   * @param filePath 文件路径
   * @returns Promise<Blob>
   */
  async readFileAsBlob(filePath: string): Promise<Blob> {
    return new Promise((resolve, reject) => {
      // #ifdef H5
      // H5环境下直接使用fetch读取
      fetch(filePath)
        .then(response => response.blob())
        .then(resolve)
        .catch(reject);
      // #endif
      
      // #ifndef H5
      // 小程序和APP环境下使用uni.getFileSystemManager
      const fs = uni.getFileSystemManager();
      fs.readFile({
        filePath,
        success: (res) => {
          const arrayBuffer = res.data as ArrayBuffer;
          const blob = new Blob([arrayBuffer], { type: 'image/jpeg' });
          resolve(blob);
        },
        fail: reject
      });
      // #endif
    });
  }
  
  /**
   * 选择性别
   * @param gender 性别
   */
  selectGender(gender: 'male' | 'female') {
    this.babyInfo.gender = gender;
    this.validateForm();
  }
  
  /**
   * 显示日期选择器
   */
  showDatePicker() {
    (this.$refs.datetimePicker as any).show();
  }
  
  /**
   * 日期选择确认
   * @param value 选择的日期值
   */
  onDateConfirm(value: any) {
    const date = new Date(value.value);
    this.babyInfo.birthDate = this.formatDate(date);
    this.validateForm();
  }
  
  /**
   * 日期选择取消
   */
  onDateCancel() {
    // 取消选择，不做任何操作
  }
  
  /**
   * 格式化日期
   * @param date 日期对象
   * @returns 格式化后的日期字符串
   */
  formatDate(date: Date): string {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  }
  
  /**
   * 验证表单
   */
  validateForm() {
    // 表单验证逻辑已在计算属性中实现
  }
  
  /**
   * 保存宝宝信息
   */
  async saveBabyInfo() {
    if (!this.isFormValid) {
      uni.showToast({
        title: '请填写必填信息',
        icon: 'none'
      });
      return;
    }
    
    this.saving = true;
    
    try {
      // 获取当前用户
      const currentUser = await getCurrentUser();
      if (!currentUser) {
        throw new Error('用户未登录，请先登录');
      }
      
      // 构建提交数据
      const submitData = {
        user_id: currentUser.id,
        name: this.babyInfo.name,
        gender: this.babyInfo.gender as 'male' | 'female',
        birth_date: this.babyInfo.birthDate,
        weight: this.babyInfo.currentWeight ? parseFloat(this.babyInfo.currentWeight) : undefined,
        height: this.babyInfo.currentHeight ? parseFloat(this.babyInfo.currentHeight) : undefined,
        preferences: {
          avatar: this.babyInfo.avatar,
          birthWeight: this.babyInfo.birthWeight ? parseFloat(this.babyInfo.birthWeight) : null,
          birthHeight: this.babyInfo.birthHeight ? parseFloat(this.babyInfo.birthHeight) : null,
          notes: this.babyInfo.notes || ''
        }
      };
      
      // 调用Supabase服务保存数据
      const savedBaby = await BabyProfileService.createBaby(submitData);
      
      if (savedBaby) {
        uni.showToast({
          title: '保存成功',
          icon: 'success'
        });
        
        // 延迟返回上一页
        setTimeout(() => {
          uni.navigateBack({
            delta: 1
          });
        }, 1500);
      } else {
        throw new Error('保存失败，请重试');
      }
    } catch (error: unknown) {
      console.error('保存宝宝信息失败:', error);
      const errorMessage = error instanceof Error ? error.message : '保存失败';
      uni.showToast({
        title: errorMessage,
        icon: 'none'
      });
    } finally {
      this.saving = false;
    }
  }
}
</script>

<style lang="scss" scoped>
.add-baby-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  
  .custom-navbar {
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    
    .navbar-content {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 44px;
      padding: 0 15px;
      
      .navbar-title {
        font-size: 18px;
        font-weight: 600;
        color: #333;
      }
      
      .navbar-right {
        width: 20px;
      }
    }
  }
  
  .form-container {
    padding: 20px 15px;
    
    .avatar-section {
      display: flex;
      justify-content: center;
      margin-bottom: 30px;
      
      .avatar-wrapper {
        position: relative;
        width: 100px;
        height: 100px;
        border-radius: 50px;
        overflow: hidden;
        background-color: #f5f5f5;
        border: 2px dashed #d0d0d0;
        
        .baby-avatar {
          width: 100%;
          height: 100%;
        }
        
        .avatar-placeholder {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 100%;
          
          .avatar-text {
            font-size: 12px;
            color: #c0c0c0;
            margin-top: 5px;
          }
        }
      }
    }
    
    .form-section {
      background-color: #ffffff;
      border-radius: 10px;
      padding: 20px;
      margin-bottom: 20px;
      
      .section-title {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        margin-bottom: 20px;
      }
      
      .form-item {
        margin-bottom: 20px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .form-label {
          display: block;
          font-size: 14px;
          color: #333;
          margin-bottom: 8px;
          
          .required {
            color: #ff4757;
          }
        }
        
        .gender-selector {
          display: flex;
          gap: 20px;
          
          .gender-option {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 15px;
            border: 2px solid #e5e5e5;
            border-radius: 8px;
            background-color: #f8f8f8;
            transition: all 0.3s;
            
            &.active {
              border-color: #007aff;
              background-color: #f0f8ff;
            }
            
            .gender-text {
              font-size: 14px;
              color: #333;
              margin-left: 8px;
            }
          }
        }
        
        .date-picker {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 12px 15px;
          border: 1px solid #e5e5e5;
          border-radius: 6px;
          background-color: #ffffff;
          
          .date-text {
            font-size: 14px;
            color: #333;
            
            &.placeholder {
              color: #c0c0c0;
            }
          }
        }
        
        .input-with-unit {
          display: flex;
          align-items: center;
          
          .unit-text {
            font-size: 14px;
            color: #666;
            margin-left: 10px;
          }
        }
        
        .textarea-input {
          width: 100%;
          min-height: 80px;
          padding: 12px 15px;
          border: 1px solid #e5e5e5;
          border-radius: 6px;
          font-size: 14px;
          color: #333;
          background-color: #ffffff;
          resize: none;
        }
      }
    }
  }
  
  .bottom-actions {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 15px;
    background-color: #ffffff;
    border-top: 1px solid #e5e5e5;
    
    .save-btn {
      width: 100%;
    }
  }
}

/* 安全区域适配 */
.add-baby-container {
  padding-bottom: env(safe-area-inset-bottom);
}
</style>